package com.wonderland.lucy.showcase.security.web;

import com.wonderland.lucy.showcase.security.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Controller
@RequestMapping("/login")
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${defaultLanguage}")
    private String defaultLanguage;

    @RequestMapping(method = {RequestMethod.GET})
    public String login() {
        return "/login";
    }

    @RequestMapping(method = {RequestMethod.POST})
    public String loginPost(User user, RedirectAttributes redirectAttributes, HttpServletRequest request) throws IOException {
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            currentUser.login(token);
        } catch (AuthenticationException e) {
            redirectAttributes.addFlashAttribute("message", "loginPrompt");
            logger.info("error", e);
            return "redirect:/login?locale=" + defaultLanguage;
        }
        if (currentUser.isAuthenticated()) {
            return "redirect:" + getSavedUrl(request);
        } else {
            redirectAttributes.addFlashAttribute("message", "loginPrompt");
            return "redirect:/login?locale=" + defaultLanguage;
        }
    }

    private String getSavedUrl(HttpServletRequest request) {
        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
        if (savedRequest == null) {
            return "/security/user";
        }
//        return savedRequest.getRequestUrl().replaceFirst(request.getContextPath(), "");
        return "/security/user";
    }
}
